#!/bin/bash

# 返回码
# 0 补丁应用成功
# 2 补丁存在冲突

# 参数校验
if [ $# -ne 7 ]; then
    echo "Usage: $0 <commit_id> <origin_branch> <user_name> <user_email> <CVE> <number> <inclusion>"
    exit 1
fi

commit_id=$1
origin_branch=$2
user_name=$3
user_email=$4
CVE=$5
number=$6
inclusion=$7

line=2
dev_branch="patch_auto_$(date +%s)"

# 全局变量存储生成的补丁文件名
generated_patch=""

linux_path="$(pwd)/stash/linux"  # 持久化仓库路径
linux_url="https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git"

kernel_path="$(pwd)/stash/kernel"
kernel_url="https://gitee.com/openeuler/kernel.git"

robot_url="https://ci-robot:03d33936c22f95aa4b47c1cce6caa790@gitee.com/ci-robot/kernel.git"

mkdir -p $(pwd)/stash

MSG="commit_msg.txt"
inclusion="mainline"
bugzilla="https://gitee.com/src-openeuler/kernel/issues/$number"
namerev="unknown"

add_str()
{
    line=$((line + 1))
    if [ -z "$1" ]; then
        sed -i "${line}{x;p;x;}" "$MSG"
    else
        sed -i "${line}i\\$1" "$MSG"
    fi
}

get_namerev() {
    namerev=$(git name-rev "$commit_id" 2>/dev/null)

    if ! echo "$namerev" | grep -q "tags/v"; then
        echo "没有找到标签"
    else
        namerev=${namerev#*/}
        namerev=${namerev%%~*}
    fi
}

add_mainline_head() {
    local ref  # 声明局部变量[7](@ref)
    
    if [ "$inclusion" = "stable" ]; then
        add_str "stable inclusion"
        add_str "from stable-$namerev"
        ref="Reference: https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/commit/?id=$commit_id"
    else
        add_str "mainline inclusion"
        add_str "from mainline-$namerev"
        ref="Reference: https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=$commit_id"
    fi
    
    add_str "commit $commit_id"
    add_str "category: bugfix"
    add_str "bugzilla: ${bugzilla}"
    add_str "CVE: ${CVE}"
    add_str ""
    add_str "$ref"
    add_str ""
    add_str "-------------------------------------------------"
    add_str ""
}

# 初始化内核仓库
init_repository() {
    local repo_dir="$1"
    local repo_url="$2"

    echo "$repo_dir $repo_url"
    if [ ! -d "$repo_dir/.git" ]; then
        echo "正在克隆仓库……"
        git clone "$repo_url" "$repo_dir"
    else
        echo "仓库 $repo_dir 已存在，跳过克隆。"
    fi
    git -C "$repo_dir" checkout master
}

# 生成内核patch
generate_patch() {
    cd "$linux_path" || { echo "无法进入 $linux_path"; exit 1; }

    echo "更新 Linux 仓库代码……"
    git pull

    echo "获取namerev"
    get_namerev
    echo "namerev: $namerev"

    # 清理旧补丁
    echo "清理旧补丁文件……"
    find . -maxdepth 1 -name "*.patch" -delete

    # 生成新补丁
    echo "为提交 $commit_id 生成补丁..."
    # 获取生成的补丁文件名
    generated_patch=$(git format-patch -1 "$commit_id" 2>/dev/null)
    if [ -z "$generated_patch" ]; then
        echo "补丁生成失败"
        exit 1
    fi
    echo "补丁生成成功：$generated_patch"

    # 复制到内核仓库
    echo "将补丁 ${generated_patch##*/} 复制到 Kernel 仓库..."
    cp "$generated_patch" "$kernel_path/${generated_patch##*/}"
    generated_patch="${generated_patch##*/}" # 仅保留文件名
    
}

# 应用patch并创建PR分支
apply_patch() {
    local patch_name="$1"
    cd "$kernel_path" || { echo "无法进入目录 $kernel_path"; exit 1; }
    echo "更新 Kernel 仓库代码……"
    git fetch origin
    echo "切换到分支 $origin_branch 并重置到远程最新状态……"
    git checkout "$origin_branch"
    git reset --hard origin/"$origin_branch"
    
    echo "开始尝试应用补丁文件：$patch"
    if ! git am "$patch_name" > /dev/null 2>&1; then
        echo "补丁应用失败，存在冲突"
        git am --abort
        exit 2
    else
        echo "补丁应用成功"
        git log -n 1 --pretty=%B > $MSG
        echo "add mainline head"
        add_mainline_head 
        sed -i '$ { /^$/d }' $MSG
        echo "添加签名信息：Signed-off-by: $user_name <$user_email>"
        echo "Signed-off-by: $user_name <$user_email>" >> $MSG  # 追加签名信息
        git commit --amend -F $MSG
    fi
    echo "执行 git reset --hard HEAD 清理工作区……"
    git reset --hard HEAD
    git remote add robot "$robot_url"

    # 检查原始目标分支是否存在
    if git ls-remote --exit-code --heads robot "$dev_branch" > /dev/null; then
        echo "目标分支 $dev_branch 已存在，自动添加后缀"
        dev_branch="${dev_branch}_tmp"
        echo "新的目标分支为 $dev_branch"
    else
        echo "目标分支 $dev_branch 不存在，将直接推送"
    fi

    # 推送代码到目标分支（自动创建不存在的分支）
    echo "推送代码到分支 $dev_branch..."
    git push robot "$origin_branch:$dev_branch" || {
        echo "推送失败，请检查权限或分支冲突"
        exit 1
    }

    # 新增基于时间的检查逻辑
    timeout=$((60*3))                   # 最大等待时间3分钟（180秒）
    start_time=$(date +%s)              # 记录开始时间戳
    branch_exists=false

    echo "开始等待分支创建（最长3分钟）..."
    while true; do
        # 检查分支是否存在
        if git ls-remote --exit-code --heads robot "$dev_branch" >/dev/null; then
            branch_exists=true
            break
        fi
        
        # 计算已用时间
        current_time=$(date +%s)
        elapsed=$((current_time - start_time))
        
        # 超时检查
        if [ $elapsed -ge $timeout ]; then
            echo "等待超时（已等待 ${elapsed} 秒），分支仍未创建"
            break
        fi
        
        # 进度提示（动态显示剩余时间）
        remaining=$((timeout - elapsed))
        echo "等待分支生效（剩余时间：${remaining}秒）..."
        sleep 5  # 保持5秒检查间隔
    done

    if [ "$branch_exists" = false ]; then
        echo "错误：推送后分支 $dev_branch 仍未在远程仓库存在"
        exit 1
    fi

    # 切换回原分支后删除临时开发分支
    git checkout "$origin_branch" 2>/dev/null || git checkout master
    echo "代码已成功推送到分支"
    echo $dev_branch
}

# 主执行流程
init_repository "$linux_path" "$linux_url"
init_repository "$kernel_path" "$kernel_url"
generate_patch
apply_patch "$generated_patch"
